// 实现 Ajax
const ajax = (opts) => {
  const { url, method, data, headers } = opts;

  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    // 三个参数：请求方法，请求路径，同步异步
    xhr.open(method, url, true);

    // 设置请求头
    for (const key in headers) {
      if (Object.hasOwnProperty.call(headers, key)) {
        xhr.setRequestHeader(key, headers[key]);
      }
    }

    // 监听 onreadystatechange() 事件，如果 readystate === 4 返回responseText
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status <= 300) {
          resolve(xhr.responseText);
        } else {
          reject(xhr);
        }
      }
    };

    xhr.send(data);
  });
};
